package com.sxpi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxpi.common.result.Result;
import com.sxpi.convert.CostumeCategoriesConvert;
import com.sxpi.convert.CostumesConvert;
import com.sxpi.mapper.CostumeImagesMapper;
import com.sxpi.mapper.CostumesMapper;
import com.sxpi.model.entity.CostumeCategories;
import com.sxpi.model.entity.CostumeImages;
import com.sxpi.model.entity.Costumes;

import com.sxpi.model.entity.CostumesVo;
import com.sxpi.service.CostumeCategoriesService;
import com.sxpi.mapper.CostumeCategoriesMapper;
import com.sxpi.model.vo.CostumeCategoriesVo;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.*;

@Service
public class CostumeCategoriesServiceImpl implements CostumeCategoriesService {
    @Resource
    private CostumeCategoriesMapper costumeCategoriesMapper;

    @Resource
    private CostumesMapper costumesMapper;

    @Resource
    private CostumeImagesMapper costumeImagesMapper;


     public Result<List<CostumeCategoriesVo>> getAllCategories() {
          LambdaQueryWrapper<CostumeCategories> eqs = new LambdaQueryWrapper<CostumeCategories>().orderByAsc(CostumeCategories::getSortOrder);
         List<CostumeCategories> costumeCategories = costumeCategoriesMapper.selectList(eqs);
        List<CostumeCategoriesVo> costumeCategoriesVos = CostumeCategoriesConvert.INSTANCE.convertEntityToVo(costumeCategories);
        costumeCategoriesVos.forEach(costumeCategoriesVo -> {
            LambdaQueryWrapper<Costumes> eq = new LambdaQueryWrapper<Costumes>().eq(Costumes::getCategoryId, costumeCategoriesVo.getPid());
            List<Costumes> costumes = costumesMapper.selectList(eq);
            List<CostumesVo> costumesVos = CostumesConvert.INSTANCE.convertVoToEntityList(costumes);
            costumesVos.forEach(costumesVo -> {
                LambdaQueryWrapper<CostumeImages> eq1 = new LambdaQueryWrapper<CostumeImages>().eq(CostumeImages::getCostumeId, costumesVo.getId());
                List<CostumeImages> costumeImages = costumeImagesMapper.selectList(eq1);
                // 查找 isMain 为 true 的图片
                CostumeImages mainImage = costumeImages.stream()
                       .filter(image -> Objects.equals(image.getIsMain(), 1))
                       .findFirst()
                       .orElse(null);
                if (mainImage!= null) {
                    costumesVo.setUrl(mainImage.getUrl());
                }
            });
            costumeCategoriesVo.setContent(costumesVos);
        });
        return Result.ok(costumeCategoriesVos);
    }

    @Override
    public Result<Map<String, Object>> getHotCostumes() {
        // 获取销量最高的服装（分页查询，只取第一页的1条记录）
        Page<Costumes> page = new Page<>(1, 1); // 第1页，每页1条记录
        LambdaQueryChainWrapper<Costumes> query = new LambdaQueryChainWrapper<>(costumesMapper)
                .orderByDesc(Costumes::getSalesVolume);

        costumesMapper.selectPage(page, query.getWrapper()); // 执行分页查询
        List<Costumes> featured = page.getRecords(); // 获取查询结果

        // 如果没有热门服装，则直接返回空结果
        if (featured.isEmpty()) {
            return Result.ok(Collections.emptyMap());
        }

        Costumes topCostume = featured.get(0); // 获取销量最高的服装

        // 查询对应服装的图片（只取第一张图片）
        LambdaQueryWrapper<CostumeImages> imageQuery = new LambdaQueryWrapper<CostumeImages>()
                .eq(CostumeImages::getCostumeId, topCostume.getId())
                .last("LIMIT 1"); // 只取第一张图片

        CostumeImages costumeImage = costumeImagesMapper.selectOne(imageQuery); // 获取服装图片

        // 组装返回的 featuredMap
        Map<String, Object> featuredMap = new HashMap<>();
        featuredMap.put("costumesId", topCostume);
        if (costumeImage != null) {
            featuredMap.put("url", costumeImage.getUrl()); // 只保存第一张图片的 URL
        }

        // 获取所有汉服分类
         Result<List<CostumeCategoriesVo>> allCategories = getAllCategories();


        // 返回结果封装
        Map<String, Object> result = new HashMap<>();
        result.put("featured", featuredMap);
        result.put("categories", allCategories);

        return Result.ok(result);
    }


}